<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.order_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   @click="handleExport">导 出
        </el-button>
      </template>
      <template #menu="scope">
        <el-button
                type="primary"
                text
                icon="el-icon-refresh"
                @click="send(scope.row)"
        >发货
        </el-button>
        <el-button
                type="primary"
                text
                icon="el-icon-refresh"
                @click="queryLogisticsInfo(scope.row)"
        >查看物流
        </el-button>
      </template>
    </avue-crud>

    <el-dialog v-model="dialogFormVisible" title="发货">
      <el-form :model="form">
        <el-form-item label="物流公司" :label-width="formLabelWidth">
          <el-select  v-model="form.data" filterable placeholder="请选择物流公司">
            <el-option
                    v-for="item in options"
                    ref = ‘mySelected’
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" :label-width="formLabelWidth">
          <el-input v-model="form.logistics_num" autocomplete="off"   placeholder="请填写物流单号" />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="sendSubmit()">
          确认
        </el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogLogisticsVisible" title="查看物流">
      <template #footer>
        <el-timeline :reverse="reverse">
          <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.ftime">
            {{activity.context}}
          </el-timeline-item>
        </el-timeline>
      <span class="dialog-footer">
        <el-button @click="dialogLogisticsVisible = false">关闭</el-button>
      </span>
      </template>
    </el-dialog>





  </basic-container>
</template>

<script >
  import {getList, getDetail, add, update, remove, logisticsDic, send, queryLogisticsInfo} from "@/api/shop/order";
  import option from "@/option/shop/order";
  import {mapGetters} from "vuex";
  import {exportBlob} from "@/api/common";
  import {getToken} from '@/utils/auth';
  import {downloadXls} from "@/utils/util";
  import {dateNow} from "@/utils/date";
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';


  export default {
    data() {
      return {
        reverse: false,
        item:{},
        form: {},
        sendForm:{},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: option,
        data: [],
        dialogFormVisible: false,
        dialogLogisticsVisible:false,
        options: [{}],
        activities: [{}]
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.order_add, false),
          viewBtn: this.validData(this.permission.order_view, false),
          delBtn: this.validData(this.permission.order_delete, false),
          editBtn: this.validData(this.permission.order_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleExport() {
        let downloadUrl = `/blade-order/order/export-order?${this.website.tokenHeader}=${getToken()}`;
        const {
            orderNum,
            createTime,
            status,
        } = this.query;
        let values = {
            orderNum_like: orderNum,
            createTime_between: createTime,
            status_equal: status,
        };
        this.$confirm("是否导出数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          NProgress.start();
          exportBlob(downloadUrl, values).then(res => {
            downloadXls(res.data, `订单管理${dateNow()}.xlsx`);
            NProgress.done();
          })
        });
      },
      queryLogisticsInfo(row){
        this.dialogLogisticsVisible = true;
        this.loading = true;
        queryLogisticsInfo(row).then(res => {
          this.loading = false;
          this.activities = res.data.data;
        });
      },
      sendSubmit(row,done){
         let param={
          "id":this.sendForm.id,
          "logisticsCode":this.form.data,
          "logisticsNum":this.form.logistics_num,
        }
        send(param).then(() => {
          this.dialogFormVisible = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          loading();
          console.log(error);
        });
      },
      send(row){
        this.dialogFormVisible = true;
        this.loading = true;
        this.sendForm = row;
        console.log("send",this.sendForm);
        logisticsDic().then(res => {
          this.loading = false;
          this.options = res.data.data;
        });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;

        const {
          orderNum,
          createTime,
          status,
        } = this.query;

        let values = {
          orderNum_like: orderNum,
          createTime_between: createTime,
          status_equal: status,
        };

        getList(page.currentPage, page.pageSize, values).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
